package com.atsmart.app.activity;

import java.io.IOException;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.ClientAdapter;
import com.atsmart.app.adapter.ClientSelectListAdapter;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.ClientInfo;
import com.atsmart.app.model.ClientListInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.LocationPageinfo;

import com.atsmart.app.sql.ClientSqlHelper;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.IntentUtil;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;
import com.google.json.JsonParseException;

public class ClientSelectListActivity extends BaseActivity implements
		LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler, OnClickListener, ClientSelectListAdapter.ClickDelegate {
	private static final String TAG = ClientSelectListActivity.class.getName();
	private ListView listView;
	private ClientListInfo datasource;
	private ClientSelectListAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private EditText txtKeyword;
	private Button btnSearch;
	private String keyword;
	private Button btnMap;
	private Gson gson;
	private ClientSqlHelper csql = null;
	private Context context;
	private boolean asyntaskIsFinished = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.client_list_layout);
		
		context = this;
		csql = new ClientSqlHelper();
		csql.open(BizApp.getInstance().getSqlHelper());
		
		gson = new Gson();
		init();
	}

	private void init(){
		txtKeyword = (EditText) findViewById(R.id.txt_keyword);
		btnSearch = (Button) findViewById(R.id.btn_search);
		btnMap = (Button) findViewById(R.id.btn_refresh);
		btnMap.setBackgroundResource(R.drawable.btn_earth_press);
		btnMap.setOnClickListener(this);
		btnSearch.setOnClickListener(this);
		listView = (ListView) findViewById(R.id.listview);
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(BizApp.getInstance().isWiFiActive() || BizApp.getInstance().isNetworkAvailable()){
			if (pageIndex == 0 && totalRow == 0){
	            showLoading();
	            asyntaskIsFinished = false;
	            getData();
	       }
		} else {
			showLoading();
			asyntaskIsFinished = false;
			getDataFromSql();
			finishedLoad(TAG);
		}
	}
	
	private void getDataFromSql(){
		int count = csql.getCount();
		if(count > 0){
			datasource = csql.getClientInfo(0, count, null);
			bindData();
		}else{
			Toast.makeText(context, "无可用网络！", Toast.LENGTH_SHORT).show();
		}
	}

	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<ClientListInfo>() {

			@Override
			protected ClientListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				CommonBody body = new CommonBody();
				if (StringUtil.isEmptyOrNull(keyword)) {
					body.setCommand(1);
				} else {
					body.setCommand(2);
				}
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion("1.0.0");
				LocationPageinfo pageInfo = new LocationPageinfo();
//				pageInfo.begin = pageIndex * pageSize;
//				pageInfo.end = (pageIndex + 1) * pageSize;
				pageInfo.begin = 0;
				pageInfo.end = 100;
				
				pageInfo.lon = BizApp.getInstance().getLon();
				pageInfo.lat = BizApp.getInstance().getLat();
				
				if (!StringUtil.isEmptyOrNull(keyword)) {
					pageInfo.name = keyword;
				}
				return ServiceHelper.getInstance().postData(
						ServiceHost.getClientsURL(),
						gson.toJson(body), gson.toJson(pageInfo), ClientListInfo.class);
			}

			@Override
			protected void runWithResult(ClientListInfo result) throws Exception {
				if (result != null) {
					if (pageIndex == 0) {
						datasource = result;
					} else {
						datasource.getClients().addAll(result.getClients());
					}
					
					
					if(csql.getCount() != datasource.getClients().size()){
						csql.delete();
						for(ClientInfo info : datasource.getClients()){
							csql.addClientInfo(info);
						}
					}
					
					bindData();
				}
				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ClientListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;
				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
				try{
					getDataByUrl2();
				}catch (Exception e) {
				}
			}
		}.execute();
	}

	private void getDataByUrl2() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<ClientListInfo>() {

			@Override
			protected ClientListInfo callService() throws IOException,
					JsonParseException, AssertionError, BizException,Exception {
				CommonBody body = new CommonBody();
				if (StringUtil.isEmptyOrNull(keyword)) {
					body.setCommand(1);
				} else {
					body.setCommand(2);
				}
				body.setImsi(BizApp.getInstance().getIMSI());
				body.setVersion("1.0.0");
				LocationPageinfo pageInfo = new LocationPageinfo();
//				pageInfo.begin = pageIndex * pageSize;
//				pageInfo.end = (pageIndex + 1) * pageSize;
				pageInfo.begin = 0;
				pageInfo.end = 100;
				
				pageInfo.lon = BizApp.getInstance().getLon();
				pageInfo.lat = BizApp.getInstance().getLat();
				
				if (!StringUtil.isEmptyOrNull(keyword)) {
					pageInfo.name = keyword;
				}
				return ServiceHelper.getInstance().postData(
						ServiceHost.getClientsURL(),
						gson.toJson(body), gson.toJson(pageInfo), ClientListInfo.class);
			}

			@Override
			protected void runWithResult(ClientListInfo result) throws Exception {
				if (result != null) {
					if (pageIndex == 0) {
						datasource = result;
					} else {
						datasource.getClients().addAll(result.getClients());
					}
					
					
					if(csql.getCount() != datasource.getClients().size()){
						csql.delete();
						for(ClientInfo info : datasource.getClients()){
							csql.addClientInfo(info);
						}
					}
					
					bindData();
				}
				asyntaskIsFinished = true;
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(ClientListInfo result, int iErrorCode)
					throws Exception {
				asyntaskIsFinished = true;
				loadingFailed(TAG, iErrorCode);
				if(PrefsUtils.getURL().equals(StringUtil.URL1)){
					PrefsUtils.setURL(StringUtil.URL2);
				}else if(PrefsUtils.getURL().equals(StringUtil.URL2)){
					PrefsUtils.setURL(StringUtil.URL1);
				}
			}
		}.execute();
	}
	
	private void bindData() {
		if (adapter == null || pageIndex == 0) {
            adapter = new ClientSelectListAdapter(datasource, this);
            adapter.setDelegate(this);
            adapter.setHandler(this);
            adapter.setClickDelegate(this);
			listView.setAdapter(adapter);
        } else {
            if (pageIndex >= 1) {
                adapter.appendDataSource(datasource);
                adapter.notifyDataSetChanged();
            }
        }
        totalRow = datasource.getRows();
        if (totalRow > (pageIndex + 1) * pageSize) {
            isNeedLoading = true;
        } else {
            isNeedLoading = false;
        }
	}

	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		 if (pageIndex * pageSize < totalRow) {
	            if (asyntaskIsFinished) {
	                pageIndex++;
	                getData();
	                asyntaskIsFinished = false;
	            }
	        }
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}

	private void showMap(){
		if (datasource == null) {
			return;
		}
		Bundle bundle = new Bundle();
		bundle.putSerializable(PersistentKeyUtil.CLIENTS_STRING, datasource);
		if(datasource != null){
			for(ClientInfo info: datasource.getClients()){
				Log.e("TAG", "经纬度 lat： = " + info.getLat() + " , lon: = " + info.getLon());
			}
		}
		IntentUtil.redirectToNext(ClientSelectListActivity.this, ClientsMapActivity.class, bundle);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refresh:
			if(BizApp.getInstance().isWiFiActive() || BizApp.getInstance().isNetworkAvailable()){
				showMap();
			}else{
				Toast.makeText(context, "无可用网络！", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.btn_search:
			keyword = txtKeyword.getText().toString().trim();
			if (StringUtil.isEmptyOrNull(keyword)) {
				Toast.makeText(this, "请输入查询关键字", Toast.LENGTH_SHORT).show();
			} else {
				showLoading();
				getData();
			}
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(int position) {
//		Log.e("aaa", "dsdsadas");
		if (adapter == null) {
			return;
		}
		ClientInfo clientInfo = (ClientInfo) adapter.getItem(position);
		PrefsUtils.setClientIdName(clientInfo.getId()+",,"+clientInfo.getName());
		Bundle bundle = new Bundle();
		IntentUtil.redirectToNext(ClientSelectListActivity.this,
				ReportActivity.class, bundle);
	}
}
